package com.thinkgem.jeesite.common.weixin;

import com.thinkgem.jeesite.common.mapper.JsonMapper;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Set;

public class HttpUtils {

    public static String doPost(String url,Map m) {
        return httpStringRequest(url,"POST", JsonMapper.toJsonString(m));
    }

    private static String post(String url,Map m){
        //创建一个post对象
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod("http://localhost:8080/");// POST请求
        Set<String> keySet = m.keySet();
        NameValuePair[] postData = new NameValuePair[keySet.size() + 1];
        int index = 0;
        for (String key : keySet) {
            postData[index++] = new NameValuePair(key, m.get(key).toString());
        }
        postData[index] = new NameValuePair("HttpRequestUrl", url);
        postMethod.addParameters(postData);
        postMethod.getParams().setParameter(
                HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
        postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        int statusCode = 0;// 发送请求
        try {
            statusCode = httpClient.executeMethod(postMethod);
            if (statusCode == HttpStatus.SC_OK) {
                // 读取内容
                byte[] responseBody = postMethod.getResponseBody();
                // 处理返回的内容
                return new String(responseBody, "utf-8");
            }
            postMethod.releaseConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 使用Get方法发送请求
     *
     * @param url
     * @return jsonstr
     */
    public static String doGet(String url) {
        String responseMsg = "";
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = null;
        try {
            getMethod = new GetMethod("http://localhost:8080/?HttpRequestUrl="+ URLEncoder.encode( url, "UTF-8" ));// GET请求
            // http超时5秒
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
            // 设置 get 请求超时为 5 秒
            getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
            getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
            httpClient.executeMethod(getMethod);// 发送请求
            // 读取内容
            byte[] responseBody = getMethod.getResponseBody();
            // 处理返回的内容
            responseMsg = new String(responseBody, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            getMethod.releaseConnection();// 关闭连接
        }
        return responseMsg;
    }


    /**
     * 发起http请求
     *
     * @param requestUrl
     * @param requestMethod
     * @param outputStr
     * @return
     */
    public static String httpStringRequest(String requestUrl, String requestMethod, String outputStr) {
        String jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try
        {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);
            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();
            // 当有数据需要提交时
            if (null != outputStr)
            {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                System.out.println("------------------------" + outputStr);
                outputStream.close();
            }
            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null)
            {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = buffer.toString();
        }
        catch (ConnectException ce)
        {
            System.out.println("Weixin server connection timed out.");
        }
        catch (Exception e)
        {
            e.printStackTrace();
            System.out.println("https request error:{}" + e);
        }
        return jsonObject;
    }
}
